<template>
    <div class="app-container">
        <div v-show="type == 0 || type == 2">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                label-width="68px">
                <el-form-item label="项目名称" prop="projectName">
                    <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="成本名目" prop="costList">
                    <el-input v-model="queryParams.costList" placeholder="请输入成本名目" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="queryParams.status" placeholder="请选择状态" style="width:230px">
                        <el-option v-for="dict in dict.type.costcontrol_status" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="loading" size="mini" height="400" :row-style="{ height: '30px' }" border
                :cell-style="{ padding: '0px' }" :data="controlList" @selection-change="handleSelectionChange">
                <el-table-column label="序号" type="index" width="45" align="center" prop="index"
                    :index="indexMethod"></el-table-column>
                <el-table-column label="合同编号" align="center" prop="contractNo" width="80"
                    :show-overflow-tooltip="true" />
                <el-table-column label="项目名称" align="center" prop="projectName" width="100"
                    :show-overflow-tooltip="true" />
                <el-table-column label="成本名目" align="center" prop="costList" :show-overflow-tooltip="true" />
                <el-table-column label="预算金额" align="center" prop="budgetAmount" width="80"
                    :show-overflow-tooltip="true" />
                <el-table-column label="实际金额" align="center" prop="actualAmount" width="70"
                    :show-overflow-tooltip="true" />
                <el-table-column label="来源" align="center" prop="source" width="70">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.cost_source" :value="scope.row.source" />
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" prop="status" width="60">

                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.costcontrol_status" :value="scope.row.status"
                            :class="{ 'text-no': scope.row.status == 0, 'text-yes': scope.row.status == 1 }" />
                    </template>
                </el-table-column>
                <el-table-column label="经手人" align="center" prop="creationName" width="70"
                    :show-overflow-tooltip="true" />
                <el-table-column label="发生时间" align="center" prop="creationTime" width="80"
                    :show-overflow-tooltip="true">

                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="确认人" align="center" prop="operateName" width="130"
                    :show-overflow-tooltip="true" />
                <el-table-column label="确认时间" align="center" prop="operateTime" width="80"
                    :show-overflow-tooltip="true">

                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
        <!-- 添加或修改成本管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="主分类" prop="classificationId">
                            <treeselect v-model="form.classificationId" :options="optionData" placeholder="请选择主分类"
                                :disabled="opt == 'details'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目名称" prop="projectName">
                            <el-input v-model="form.projectName" placeholder="请点击选择项目" :disabled="form.source == '0'"
                                :readonly="readonly" @focus="getProjectAll" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>

                    <el-col :span="12">
                        <el-form-item label="合同编号" prop="contractNo">
                            <el-input v-model="form.contractNo" placeholder="合同编号" disabled="true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="成本名目" prop="costList">
                            <el-input v-model="form.costList" placeholder="请输入成本名目" :disabled="form.source == '0'" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>


                    <el-col :span="12">
                        <el-form-item label="预算金额" prop="budgetAmount">
                            <el-input v-model="form.budgetAmount" placeholder="请输入预算金额"
                                :disabled="form.source == '0'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="实际金额" prop="actualAmount">
                            <el-input v-model="form.actualAmount" placeholder="请输入实际金额" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>

                    <el-col :span="12">
                        <el-form-item label="经手人" prop="creationName">
                            <el-input v-model="form.creationName" placeholder="请输入经手人" :disabled="form.source == '0'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="发生时间" prop="creationTime">
                            <el-date-picker clearable :disabled="form.source == '0'" v-model="form.creationTime"
                                type="date" value-format="yyyy-MM-dd" placeholder="请选择发生时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="node">
                            <el-input v-model="form.node" placeholder="请输入备注" type="textarea"
                                :autosize="{ minRows: 3, maxRows: 4 }" :disabled="opt == 'details'" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

        </el-dialog>
        <el-dialog :title="titleClass" :visible.sync="openMainClass" width="450px" append-to-body>
            <el-form ref="formClass" :model="formClass" :inline="true">
                <el-form-item label="主分类" prop="classificationId" label-width="80px">
                    <treeselect v-model="formClass.classificationId" :options="optionData" placeholder="请选择主分类"
                        style="width: 300px" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitClassForm()">确 定</el-button>
                <el-button @click="cancelClass">关 闭</el-button>
            </div>
        </el-dialog>
        <!-- 项目选择界面 -->
        <el-dialog :title="titlePojectAll" :visible.sync="openProjectAll" width="1020px" append-to-body>
            <el-row>
                <!-- <el-col :span="5">
                <MainType :typeCode="typeProjectCode" @getNode="getNode"></MainType>
              </el-col> -->
                <el-col :span="25">
                    <el-form :model="queryProjectParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                        label-width="68px">
                        <el-form-item label="项目编号" prop="projectNumber">
                            <el-input v-model="queryProjectParams.projectNumber" style="width:165px"
                                placeholder="请输入项目编号" clearable @keyup.enter.native="handleQuery" />
                        </el-form-item>
                        <el-form-item label="项目名称" prop="projectName">
                            <el-input v-model="queryProjectParams.projectName" style="width:170px" placeholder="请输入项目名称"
                                clearable @keyup.enter.native="handleQuery" />
                        </el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        <el-button type="primary" size="mini" @click="saveProject">确定</el-button>
                    </el-form>
                    <el-table v-loading="loading" ref="tableProject" height="400"
                        @selection-change="handleSelectionChangeProject" :row-style="{ height: '30px' }" border
                        :cell-style="{ padding: '0px' }" :data="projectInfoList">
                        <el-table-column type="selection" width="55" align="center" />
                        <el-table-column label="序号" type="index" align="center" prop="index" width="50"
                            :index="indexMethod" :show-overflow-tooltip="true"></el-table-column>
                        <el-table-column label="项目编号" align="center" prop="projectNumber" width="100"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="项目名称" align="center" width="135" prop="projectName"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="项目负责人" align="center" prop="projectLeader" width="120"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="立项方式" align="center" :formatter="typeFormat" prop="projectType"
                            width="70" :show-overflow-tooltip="true" />
                        <el-table-column label="计划开始时间" align="center" prop="startTime" width="95"
                            :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column label="计划结束时间" align="center" prop="endTime" width="95"
                            :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column label="状态" align="center" prop="state" width="55">

                            <template slot-scope="scope">
                                <dict-tag :options="dict.type.project_status" :value="scope.row.state" />
                            </template>
                        </el-table-column>
                        <el-table-column label="创建人" align="center" prop="creationName" width="120"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="创建时间" align="center" prop="creationTime" width="85"
                            :show-overflow-tooltip="true">

                            <template slot-scope="scope">
                                <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="totalProject > 0" :total="totalProject" :page.sync="queryProjectParams.pageNum"
                        :limit.sync="queryProjectParams.pageSize" @pagination="getProjectListAll" />
                </el-col>
            </el-row>
        </el-dialog>
        <!-- 项目选择界面 結束 -->

    </div>
</template>

<script>
import { editMainClass, listControl, getControl, delControl, addControl, updateControl } from "@/api/project/control";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import MainType from "@/components/MainType/index";
import { listType } from "@/api/maintype/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listContractInfo, getContractInfo } from "@/api/contract/info";
import { listProjectInfoAll } from "@/api/project/projectInfo";
export default {
    dicts: ['costcontrol_status', 'project_status', 'cost_source'],
    components: { MainType, Treeselect },
    name: "Control",
    props: {
        id: {
            type: String,
            default: ""
        },
    },
    data() {
        var projectName = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('项目名称不能为空'));
            }
            return callback()
        };
        return {
            //主分类 -----开始
            type: 0,
            formClass: {},
            titleClass: "修改主分类",
            optionData: null,
            openMainClass: false,
            typeCode: 'cost',
            //主分类 -----结束

            //项目选择--开始
            totalProject: 0,
            titlePojectAll: '项目选择',
            openProjectAll: false,
            //项目选择--结束

            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 成本管理表格数据
            controlList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            //项目查询参数
            queryProjectParams: {
                pageNum: 1,
                pageSize: 15,
                state: null,
                projectName: null,
                projectNumber: null,
                startTime: null,
                endTime: null,
                attackTime: null,
                completeTime: null,

            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 15,
                classificationId: null,
                contractNo: null,
                projectId: null,
                projectName: null,
                costList: null,
                budgetAmount: null,
                actualAmount: null,
                status: null,
                node: null,
                creationId: null,
                creationName: null,
                creationTime: null,
                operateId: null,
                operateName: null,
                operateTime: null,
            },
            contractNo: null,
            contractName: null,
            contractId: null,
            projectName: null,
            projectId: null,
            contractList: [],
            total1: 0,
            status: [],
            // 表单参数
            form: {
                classificationId: '650c44e1-b575-4b62-9d54-1ba9d1e8abb7',
                creationTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
            },
            // 表单校验
            rules: {


                costList: [
                    { required: true, message: "成本条目不能为空", trigger: "blur" },
                    { max: 100, message: '成本条目不能超过100字', trigger: 'blur' }
                ],
                creationName: [
                    { required: true, message: "经手人不能为空", trigger: "blur" },
                ],
                projectName: [
                    { required: true, validator: projectName, trigger: "change" }
                ],
                budgetAmount: [
                    { required: true, message: "预算金额不能为空", trigger: "blur" },
                    {
                        //pattern: /^[1-9]\d*$/,
                        //金额校验 保留两位小数
                        pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
                        message: "请输入正确的金额，可保留两位小数",
                        trigger: "blur"
                    }
                ],
                actualAmount: [
                    { required: true, message: "实际金额不能为空", trigger: "blur" },
                    {
                        //pattern: /^[1-9]\d*$/,
                        //金额校验 保留两位小数
                        pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
                        message: "请输入正确的金额，可保留两位小数",
                        trigger: "blur"
                    }
                ],
                creationTime: [
                    { required: true, message: "发生时间不能为空", trigger: "change" }
                ],

            },
        };
    },
    created() {
        this.getList();
        this.listType();
        this.getProjectListAll();
    },
    methods: {
        //修改主分类
        editMainClass() {
            if (this.ids.length == 0) {
                this.$message.error("请选择要修改的信息！");
            } else {
                for (let index = 0; index < this.status.length; index++) {
                    if (this.status[index] == 1) {
                        this.$message.error("已完结的项目不允许再修改！");
                        return
                    } else {
                        this.resetClass();
                        this.openMainClass = true;
                    }
                }

            }
        },
        //序号
        indexMethod(index) {
            return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
        },
        typeFormat(row, column) {
            var status = [];
            if (row.projectType == 1) {
                status.push("合同");
            } else {
                status.push("产品");
            }
            return status.join("");
        },
        //客户选择界面
        getProjectAll() {
            this.openProjectAll = true;
            //this.$refs.tableProject.clearSelection();
        },
        indexMethod(index) {
            return (this.queryProjectParams.pageNum - 1) * this.queryProjectParams.pageSize + index + 1;
        },
        //保存选择的项目信息
        saveProject() {
            if (this.projectName == "" || this.projectName == null) {
                this.$modal.msgError("请先选择项目！");
            } else {
                this.openProjectAll = false
                //this.form.contractName = ""
                //this.form.projectName= ""
                this.form.contractId = this.contractId.toString()
                getContractInfo(this.contractId).then(response => {
                    this.contractNo = response.data.contractNumber
                    this.$set(this.form, 'contractNo', response.data.contractNumber)
                });
                this.form.projectId = this.projectId.toString()
                this.$set(this.form, 'projectName', this.projectName.toString())
                //this.$set(this.form, 'contractId', this.contractId)
            }
        },
        //项目信息反显
        handleSelectionChangeProject(selection) {
            if (selection.length > 1) {
                this.$refs.tableProject.clearSelection(); // 清空所有选择
                this.$refs.tableProject.toggleRowSelection(selection.pop()); // 设置选择项
            } else {

                this.contractId = selection.map(item => item.contractId)//單選
                this.contractName = selection.map(item => item.contractName)
                this.projectId = selection.map(item => item.projectId)
                this.projectName = selection.map(item => item.projectName)
                // this.single = selection.length !== 1
                // this.multiple = !selection.length
            }

        },
        /** 查询所有项目信息列表 */
        getProjectListAll() {
            this.loading = true;
            listProjectInfoAll(this.queryParams).then(response => {
                this.projectInfoList = response.rows;
                this.totalProject = response.total;
                this.loading = false;
            });
        },

        //获取树节点数据
        listType() {
            listType({ typeCode: 'cost' }).then(res => {
                this.optionData = res.data;
            })
        },
        //主分类树点击事件
        getNode(data, node, obj) {
            this.queryParams.classificationId = data.id
            this.getList()
        },
        cancelClass() {
            this.openMainClass = false;
            this.resetClass();
        },
        submitClassForm() {
            if (this.formClass.classificationId == "undefined" || this.formClass.classificationId == "" || this.formClass.classificationId == null) {
                this.$message.error("请选择主分类！");
            } else {
                const params = {
                    businessId: this.ids.toString(),
                    mainClassId: this.formClass.classificationId,
                };
                editMainClass(params).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.openMainClass = false;
                    this.getList();
                });
            }
        },
        resetClass() {
            this.formClass = {
                classificationId: null,
            }
        },
        /** 查询成本管理列表 */
        getList() {
            this.loading = true;
            this.queryParams.projectId = this.id;
            listControl(this.queryParams).then(response => {
                this.controlList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                projectId: null,
                costList: null,
                amount: null,
                status: null,
                delFlag: null,
                operateId: null,
                departmentId: null,
                departmentName: null,
                organizationId: null,
                organizationName: null,
                creationTime: null,
                operateTime: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.status = selection.map(item => item.status)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加成本管理";
            this.form.classificationId = '650c44e1-b575-4b62-9d54-1ba9d1e8abb7'
            this.form.creationTime = this.parseTime(new Date(), '{y}-{m}-{d}')
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getControl(id).then(response => {
                console.log(response.data)
                this.form = response.data;
                this.open = true;
                this.title = "修改成本管理";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateControl(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addControl(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 确认按钮操作 */
        handleConfirm(row) {
            const ids = row.id || this.ids;
            this.form.id = row.id
            this.form.status = 1
            this.$modal.confirm('确认后不允许再修改，是否确认成本条目为"' + row.costList + '"的数据项？').then(function () {
            }).then(() => {
                updateControl(this.form).then(response => {
                    this.getList();
                    this.$modal.msgSuccess("确认成功");
                });

            }).catch(() => { });
        },

        /** 导出按钮操作 */
        handleExport() {
            this.download('control/control/export', {
                ...this.queryParams
            }, `control_${new Date().getTime()}.xlsx`)
        }
    }
};
</script>

<style>
.text-no {
    color: red;
}

.text-yes {
    color: green;
}
</style>
